import logging
from typing import Dict, Any

from flask import Blueprint

from app.utils.laser_utils import LaserUtils
from mysql_tool.mysql_tool import MySQLTool

smt1laser_bp = Blueprint('smt1laser', __name__)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def get_smt(mysql_tool, serial_number):
    """根据流水号查询对应的物料信息，只返回第一个工单码"""
    logger.info(f"查询流水号对应的工单码: {serial_number}")

    smt_sql = """
              SELECT sbmr.wo_code
              FROM smt_npm_scan_batch_material_relation sbmr
              WHERE \
                  sbmr.batch_code = (SELECT a.batch_code FROM smt_npm_scan_record a WHERE a.serial_number = %s LIMIT 1)
              """

    try:
        results = mysql_tool.execute_query(smt_sql, (serial_number,))
        if results and len(results) > 0:
            return results[0][0]
        return None
    except Exception as e:
        logger.error(f"查询工单码失败: {str(e)}")
        return None


@smt1laser_bp.route('/query/<string:serial_number>', methods=['GET'])
def check_serial(serial_number: str) -> Dict[str, Any]:
    """根据流水号查询对应文件中是否存在该记录"""
    # 验证流水号格式
    if not serial_number.startswith('S'):
        return {
            "code": 400,
            "message": "流水号格式错误，必须以S开头",
            "data": None
        }

    try:
        # 解析流水号
        date_time = LaserUtils.parse_serial_number(serial_number)
        if not date_time:
            return {
                "code": 400,
                "message": "无法解析流水号日期",
                "data": None
            }

        # 获取可能的文件路径
        file_paths = LaserUtils.get_smt1_log_paths(serial_number, days_range=[-2, -1, 0, 1])

        if not file_paths:
            return {
                "code": 200,
                "message": f"未找到与流水号 {serial_number} 相关的日志文件",
                "data": None
            }

        # 在文件中查找记录
        for file_path in file_paths:
            record = LaserUtils.find_record(file_path, serial_number)
            if record:
                # 提取产品信息
                product_info = LaserUtils.extract_product_info(record)

                # 创建MySQL工具实例并查询工单码
                mysql_tool = MySQLTool()
                wo_code = None
                if mysql_tool.connect():
                    wo_code = get_smt(mysql_tool, serial_number)

                result = {
                    "code": 200,
                    "message": "success",
                    "data": {
                        "confirm_id": f"CONF-{serial_number}",
                        "serial_number": serial_number,
                        "date": date_time.strftime("%Y-%m-%d"),
                        "file_path": file_path,
                        "record": record,
                        "wo_code": wo_code
                    }
                }

                # 添加产品信息
                if product_info:
                    result["data"].update({
                        "product_code": product_info.get("short_product_code", ""),
                        "board_side": product_info.get("board_side", ""),
                        "laser_time": product_info.get("laser_time", ""),
                        "full_product_code": product_info.get("full_product_code", "")
                    })

                return result

        # 所有文件都没找到
        return {
            "code": 200,
            "message": f"未找到流水号 {serial_number} 的相关信息",
            "data": None
        }

    except Exception as e:
        logger.error(f"查询过程发生错误: {str(e)}", exc_info=True)
        return {
            "code": 500,
            "message": f"查询过程发生错误: {str(e)}",
            "data": None
        }
